package cc.aliza.lib.mongo.core;

import cc.aliza.lib.mongo.core.cache.DBCache;
import cc.aliza.lib.mongo.core.exception.DBConnectionException;
import cc.aliza.lib.mongo.core.utils.StringUtil;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoClientURI;
import com.mongodb.client.MongoDatabase;

/**
 * 『给时光以生命·给岁月以文明』
 *
 * @author Zhang Jing (byrdkm17@gmail.com).
 */
public class AlizaConnection {

    private MongoClient mc;

    private boolean connected = false;

    private String prefix;

    public static AlizaConnection getInstance() {
        return Holder.instance;
    }

    public void connect(String uri, String prefix) {
        connect(uri, prefix, new MongoClientOptions.Builder());
    }

    public synchronized void connect(String uri, String prefix, MongoClientOptions.Builder builder) {
        if (!connected) {
            mc = new MongoClient(new MongoClientURI(uri, builder));
            connected = true;
            this.prefix = prefix;
        }
    }

    public MongoDatabase getDB(String name) {
        if (mc == null) {
            throw new DBConnectionException("Can not get database instance! Please ensure connected to mongoDB correctly.");
        }
        if (StringUtil.isEmpty(prefix)) {
            return DBCache.getInstance().get(mc, name);
        } else {
            return DBCache.getInstance().get(mc, prefix + "_" + name);
        }
    }

    public String getPrefix() {
        return prefix;
    }

    private static class Holder {
        static final AlizaConnection instance = new AlizaConnection();
    }
}
